package com.mc.fastkit.utils

import android.provider.Settings
import android.provider.Settings.SettingNotFoundException
import android.view.Window
import androidx.annotation.IntRange
import com.mc.fastkit.ext.app

/**
 * 屏幕亮度工具
 * @author: MasterChan
 * @date: 2023-01-05 17:51
 */
object BrightnessUtils {

    /**
     * 是否开启自动亮度
     * @return Boolean
     */
    fun isEnabledAutoBrightness(): Boolean {
        return try {
            val mode = Settings.System.getInt(
                app.contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE
            )
            mode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC
        } catch (e: SettingNotFoundException) {
            e.printStackTrace()
            false
        }
    }

    /**
     * 开启自动亮度
     * @param enabled Boolean
     * @return Boolean
     */
    fun enableAutoBrightness(enabled: Boolean): Boolean {
        return Settings.System.putInt(
            app.contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE,
            if (enabled) {
                Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC
            } else {
                Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL
            }
        )
    }

    /**
     * 获取屏幕亮度
     * @return Int
     */
    fun getBrightness(): Int {
        return try {
            Settings.System.getInt(app.contentResolver, Settings.System.SCREEN_BRIGHTNESS)
        } catch (e: SettingNotFoundException) {
            e.printStackTrace()
            0
        }
    }

    /**
     * 设置屏幕亮度
     * @param brightness Int
     * @return Boolean
     */
    fun setBrightness(@IntRange(from = 0, to = 255) brightness: Int): Boolean {
        val result = Settings.System.putInt(
            app.contentResolver, Settings.System.SCREEN_BRIGHTNESS, brightness
        )
        app.contentResolver.notifyChange(
            Settings.System.getUriFor("screen_brightness"), null
        )
        return result
    }

    /**
     * 设置窗口亮度
     * @param window     窗口
     * @param brightness 亮度值
     */
    fun setWindowBrightness(window: Window, @IntRange(from = 0, to = 255) brightness: Int) {
        val lp = window.attributes
        lp.screenBrightness = brightness / 255f
        window.attributes = lp
    }

    /**
     * 获取窗口亮度
     * @param window 窗口
     * @return 屏幕亮度 0-255
     */
    fun getWindowBrightness(window: Window): Int {
        val lp = window.attributes
        val brightness = lp.screenBrightness
        return if (brightness < 0) getBrightness() else (brightness * 255).toInt()
    }
}